<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<style>
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
			border: none;
			list-style: none;
		}
		
		.box {
			display: flex;
			height: 100dvh;
			width: 100%;
			justify-content: center;
			align-items: center;
			
			.input-box {
				background-color: #fafafa;
				border: 1px dashed #b9b9b9;
				width: 200px;
				height: 200px;
				border-radius: 5px;
				position: relative;
				cursor: pointer;
				display: inline-block;
				
				input[type=file] {
					display: inline-block;
					width: 100%;
					height: 100%;
					opacity: 0;
				}
				
				span {
					font-size: 60px;
					color: #b4b4b4;
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					user-select: none;
				}
			}
		}
		
		img {
			width: 200px;
			height: 200px;
			border-radius: 5px;
			object-fit: cover;
			margin-left: 5px;
			display: none;
		}
	</style>
</head>
<body>
	<div class="box">
		<label class="input-box" for="fileInput">
			<!-- 选择图片 -->
			<input type="file" id="fileInput">
			<span>+</span>
		</label>
		<!-- 预览图片 -->
		<img src="#" alt="" class="previewImage">
	</div>
	
	<script>
		// 获取选择文件输入框
		const selectFile = document.querySelector('input[type=file]')
		// 监听事件
		selectFile.addEventListener('change', async (e) => {
			// 文件对象
			const file = e.target.files[0]
			// 转换为formData对象
			const formData = new FormData()
			// 添加数据
			formData.append('img', file)
			// 上传图片
			const response = await fetch('http://hmajax.itheima.net/api/uploadimg', {
				method: 'POST',
				body: formData
			})
			// 获取后端返回结果
			const data = await response.json()
			// 获取预览图片标签
			const previewImage = document.querySelector('.previewImage')
			// 预览图片
			previewImage.src = data?.data?.url
			previewImage.style.display = 'block'
			
			// 本地预览
			// const fileReader = new FileReader()
			// fileReader.onload = (e) => {
			// 	previewImage.src = e.target.result
			// 	previewImage.style.display = 'block'
			// }
			// fileReader.readAsDataURL(file)
		})
	</script>
</body>
</html>